package com.mrlv.rabbitmq;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 售票例子
 * @author Mrlv
 * @date 2021年11月17日 16:14
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() ->{ for (int i = 0; i < 30; i++) { ticket.saleTicket(); } }, "客户1").start();
        new Thread(() ->{ for (int i = 0; i < 30; i++) { ticket.saleTicket(); } }, "客户2").start();
        new Thread(() ->{ for (int i = 0; i < 30; i++) { ticket.saleTicket(); } }, "客户3").start();
    }
}


class Ticket {

    private int number = 30;

    //可重入锁
    private Lock lock = new ReentrantLock();

    public void saleTicket(){

        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第：" + (number--) + "\t，还剩：" + number );
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
}
